#/usr/bin/bash
java -version

if [ $? -ne 0  ];then
	echo "--------------请先安装jdk,退出脚本------------"
	exit
fi


INSTALL_PATH=$1
if [ ! $INSTALL_PATH ];then
	INSTALL_PATH="/usr/local/zookeeper"
fi

#zookeeper架包下载路径,不传默认ftp://ftpUser:123456@175.178.190.189/zookeeper/zookeeper-3.8.0/apache-zookeeper-3.8.0-bin.tar.gz
DOWNLOAD_URL=$2
if [ ! $DOWNLOAD_URL ];then
	DOWNLOAD_URL="ftp://ftpUser:123456@175.178.190.189/zookeeper/zookeeper-3.8.0/apache-zookeeper-3.8.0-bin.tar.gz"
fi

#zookeeper端口号
ZOOKEEPER_PORT=$3

if [ ! $ZOOKEEPER_PORT  ];then
	ZOOKEEPER_PORT=2181
fi

#如果文件夹不存在，创建文件夹
if [ ! -d $INSTALL_PATH ];then
   mkdir $INSTALL_PATH
fi

cd $INSTALL_PATH

#wget下载文件
wget $DOWNLOAD_URL

##获取文件名
FILENAME=${DOWNLOAD_URL##*/};

#判断当前文件是什么压缩包
if [ ${FILENAME##*.} = gz ];then
  TEMP=${FILENAME%.*}
    if [ ${TEMP##*.} = tar ];then
        tar -zxvf $FILENAME -C $INSTALL_PATH
    else
        unzip  $FILENAME -d  $INSTALL_PATH
    fi
elif [ ${FILENAME##*.} = zip ];then
    unzip  $FILENAME -d  $INSTALL_PATH
fi


#获取解压后当前目录下的文件名
NEW_FILENAME=`ls -lt $INSTALLPATH |grep zookeeper|head -n 1|awk '{print $9}'`;

if [ ! $NEW_FILENAME ];then
  echo "解压失败，获取不到解压后的文件名，退出脚本";
  exit
fi

#删除安装包
rm -rf $INSTALL_PATH/$FILENAME

cd $NEW_FILENAME/conf

cp zoo_sample.cfg zoo.cfg

#修改jvm启动参数
sed -i "/^.*clientPort=2181.*$/a    clientPort=$ZOOKEEPER_PORT" zoo.cfg
sed -i "N;/\n.*clientPort=$ZOOKEEPER.*/!P;D" zoo.cfg


cd /etc/profile.d/


#创建zookeeper_env.sh文件并配置环境变量
#先判断文件是否已经存在，若存在先删除
if [ -f zookeeper_env.sh ];then
	rm -rf zookeeper_env.sh;
fi

#配置zookeeper环境变量
cat >>/etc/profile.d/zookeeper_env.sh<<EOF 
export ZOOKEEPER_HOME=$INSTALL_PATH/$NEW_FILENAME
export PATH=\$ZOOKEEPER_HOME/bin:\$PATH
EOF

#重启/ect/profile环境
source /etc/profile

#启动zookeeper服务
zkServer.sh start

if [ $? -ne 0 ]; then
    echo "zookeeper启动失败，请排查原因，退出脚本";
    exit;
else
    echo "zookeeper 启动成功，请稍后手动登录云服务器,在安全组中放通$ZOOKEEPER_PORT端口";
fi
